//
//  SDPaientInfoMgr.m
//  TestSL
//
//  Created by pcyang on 16/7/7.
//  Copyright © 2016年 pcyang. All rights reserved.
//

#import "SDPaientInfoMgr.h"
#import "FMDatabase.h"
#import "SDPaientInfoItem.h"
#import "SDPhotoInfo.h"
#import <objc/runtime.h>

static FMDatabase *fmdb = nil;

@interface SDPaientInfoMgr ()
@property (nonatomic,retain) NSString   *localCacheDirectory;
@end

@implementation SDPaientInfoMgr

- (instancetype)init{
    if (self = [super init]) {
        
        static dispatch_once_t oneToken;
        dispatch_once(&oneToken, ^{
            NSString *document = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
            NSString *filePath = [document stringByAppendingPathComponent:@"database.sqlite"];
          //  NSLog(@"%@",document);
            fmdb = [FMDatabase databaseWithPath:filePath];
            
            [self creatTable:[SDPaientInfoItem class] tableName:kPaientTableName keyName:nil primaryKey:nil];


        });
    }
    return self;
}

+ (SDPaientInfoMgr*)shareAGDatabaseManager{
    return [[SDPaientInfoMgr alloc]init];
}

- (BOOL)creatTable:(Class)cls tableName:(NSString*)tbName keyName:(NSString*)keyName primaryKey:(NSString*) key{
    
    NSArray *array = [self getModelAllProperty:cls];
    NSMutableString *sql = [NSMutableString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (",tbName];
    
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dic = array[i];
        [sql appendFormat:@"%@  %@ ",[dic objectForKey:@"name"],[dic objectForKey:@"type"]];
        if(keyName != nil && [keyName isEqualToString:[dic objectForKey:@"name"]]){
            [sql appendString:key];
        }
        if (i < array.count - 1){
            [sql appendString:@","];
        }
    }
    
    [sql appendString:@")"];
    
  //  NSLog(@"创建表格: %@",sql);
    
    [fmdb open];
    BOOL result = [fmdb executeUpdate:[sql copy]];
    //NSLog(@"创建表格:%@",result ? @"成功":@"失败");
    [fmdb close];
    return result;
}

- (BOOL)insert:(id)model tableName:(NSString*)tbName{
    
    NSArray *array = [self getModelAllProperty:[model class]];
    
    NSMutableString *propertyStr = [[NSMutableString alloc]init];
    NSMutableString *valuesStr = [[NSMutableString alloc]init];
    
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dic = array[i];
        [propertyStr appendString:[dic objectForKey:@"name"]];
        NSString* tempValue = [model valueForKey:[dic objectForKey:@"name"]];
        if (tempValue == nil) {
            tempValue = @"";
        }
        [valuesStr appendFormat:@"'%@'",tempValue];
        
        if (i < array.count - 1){
            [propertyStr appendString:@","];
            [valuesStr appendString:@","];
        }
    }
    NSMutableString *sql = [NSMutableString stringWithFormat:@"INSERT INTO %@ (%@) values (%@)",tbName,propertyStr ,valuesStr];
   // NSLog(@"添加数据 : %@",sql);
    [fmdb open];
    BOOL result = [fmdb executeUpdate:[sql copy]];
    [fmdb close];
    //NSLog(@"添加数据:%@",result ? @"成功":@"失败");
    
    return result;
}

- (BOOL)update:(id)model tableName:(NSString*)tbName where:(NSString*)str{
    NSArray *array = [self getModelAllProperty:[model class]];
    NSMutableString *sql = [NSMutableString stringWithFormat:@"UPDATE %@ SET ",tbName];
    
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dic = array[i];
        NSString *pro = [dic objectForKey:@"name"];
        NSString* tempValue = [model valueForKey:pro];
        if (tempValue == nil) {
            tempValue = @"";
        }
        [sql appendFormat:@"%@ = '%@'",pro,tempValue];
        if (i < array.count - 1){
            [sql appendString:@","];
        }
    }
    
    [sql appendFormat:@" where %@",str];
    
 //   NSLog(@"修改数据 : %@",sql);
    [fmdb open];
    BOOL result = [fmdb executeUpdate:[sql copy]];
    [fmdb close];
   // NSLog(@"更新数据:%@",result ? @"成功":@"失败");
    return result;
}


- (BOOL)deleteTableName:(NSString*)tbName where:(NSString*)str{
    NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@",tbName,str];
 //   NSLog(@"删除数据 : %@",sql);
    [fmdb open];
    BOOL result = [fmdb executeUpdate:sql];
    [fmdb close];
   // NSLog(@"更新数据:%@",result ? @"成功":@"失败");
    return result;
}


- (NSArray*)select:(Class)model tableName:(NSString*)tbName where:(NSString*)str{
    NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@",tbName,str];
    NSArray *array = [self propertiesInModel:[model class]];
    [fmdb open];
    FMResultSet *set = [fmdb executeQuery:sql];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    NSMutableArray *allArray = [[NSMutableArray alloc]init];
    while ([set next]) {
        for (int i = 0; i < array.count; i++) {
            NSString* propertyName = array[i];
            [dic setValue:[set stringForColumn:propertyName] forKey:propertyName];
        }
        
        id object = [[model alloc] initWithInfo:dic];
        [allArray addObject:object];
    }
    
    [set close];
    [fmdb close];
    return [allArray copy];
}

- (NSArray*)selectALL:(Class)model tableName:(NSString*)tbName {
    NSString *sql = [NSString stringWithFormat:@"select * from %@ ",tbName];
    NSArray *array = [self propertiesInModel:[model class]];
    [fmdb open];
    FMResultSet *set = [fmdb executeQuery:sql];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    NSMutableArray *allArray = [[NSMutableArray alloc]init];
    while ([set next]) {
        for (int i = 0; i < array.count; i++) {
            NSString* propertyName = array[i];
            [dic setValue:[set stringForColumn:propertyName] forKey:propertyName];
        }
        
        id object = [[model alloc] initWithInfo:dic];
//        NSString * name = [set stringForColumn:@"name"];
//        NSString * birthday = [set stringForColumn:@"birthday"];
//        NSString * avatarFileName = [set stringForColumn:@"avatarFileName"];
//        long  sId = [set longForColumn:@"sId"];
//        SDPaientInfoItem* suffererItem = [[SDPaientInfoItem class] alloc];
//        suffererItem.name = name;
//        suffererItem.sId = sId;
//        suffererItem.birthday = birthday;
//        suffererItem.avatarFileName = avatarFileName;
        
        [allArray addObject:object];
    }
    
    [set close];
    [fmdb close];
    return [allArray copy];
}

- (NSArray *)propertiesInModel:(id)model {
    if (model == nil) {
        return nil;
    }
    
    NSMutableArray *propertiesArray = [[NSMutableArray alloc] init];
    
    NSString *className = NSStringFromClass([model class]);
    id classObject = objc_getClass([className UTF8String]);
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList(classObject, &count);
    
    for (int i = 0; i < count; i++) {
        // 取得属性名
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property)
                                                          encoding:NSUTF8StringEncoding];
        [propertiesArray addObject:propertyName];
    }
    
    return [propertiesArray copy];
}

#pragma mark --- 辅助方法 ---
- (NSArray *)getModelAllProperty:(Class)cls{
    
    unsigned int count = 0;
    objc_property_t *propertys = class_copyPropertyList(cls, &count);
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < count; i++) {
        
        objc_property_t property = propertys[i];
        NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        if ([propertyName isEqualToString:@"selected"]) {   //现在这里过滤掉photoinfo的selected属性
            continue;
        }
        
        NSString *type = [self getPropertyAttributeValue:property name:@"T"];
        
        if ([type isEqualToString:@"q"]||[type isEqualToString:@"i"]) {
            type = @"INTEGER";
        }else if([type isEqualToString:@"f"] || [type isEqualToString:@"d"]){
            type = @"FLOAT";
        }else{
            type = @"TEXT";
        }
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:propertyName , @"name",type , @"type", nil];
        
        [array addObject:dic];
        
    }
    free(propertys);
    
    return array.copy;
}

/**
 *  获取属性的特征值
 */

- (NSString*)getPropertyAttributeValue:(objc_property_t) pro name:(NSString*)name{
    
    unsigned int count = 0;
    objc_property_attribute_t *attributes = property_copyAttributeList(pro, &count);
    
    for (int i = 0 ; i < count; i++) {
        objc_property_attribute_t attribute = attributes[i];
        if (strcmp(attribute.name, name.UTF8String) == 0) {
            return [NSString stringWithCString:attribute.value encoding:NSUTF8StringEncoding];
        }
    }
    free(attributes);
    return nil;
}
@end
